import { Component, OnInit } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { LocalStorageService } from '../../../service/localStorageService/local-storage.service';


import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import { HttpService } from '../../../service/httpService/http.service';
import { signln } from '../../../urlConfig';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.styl']
})
export class LoginComponent implements OnInit {

  validateForm: FormGroup;
  token: any = {
    accessToken: '', // 访问令牌
    refreshToken: '',  // 刷新令牌
    role: '', // 权限等级
  }

  constructor(private fb: FormBuilder,
    public http: HttpService,
    private notification: NzNotificationService,
    private router: Router,
    public localStorage: LocalStorageService,
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: ['', [Validators.required, Validators.pattern(/^[0-9]{10}$/)]],
      password: ['', [Validators.required]],
      remember: [true]
    });
    localStorage.removeItem('token');
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    var from = this.validateForm.value
    var account = {
      username: from.userName,
      password: from.password
    }
    this.http.postData(signln, account).subscribe((event: any) => {
      if (event.code === 210) { // 
        this.DuplicateSubmission('error');
      } else if (event.code === 200) {
        this.token.accessToken = event.result.access_token;
        this.token.refreshToken = event.result.refresh_token;
        this.token.role = event.result.role;
        this.localStorage.setItem('token', this.token);
        
        this.router.navigate(['/home/upload']);

      }
      // // 记住密码
      // if (from.remember) {
      //   this.localStorage.setItem('token', this.token);
        // }
    })
  }

  DuplicateSubmission(type: string): void {
    this.notification.create(
      type,
      '登陆失败',
      '用户名或密码错误！'
    );
  }

}
